<!--
 * @Descripttion: 1
 * @version: 1
 * @Author: ErCHen
 * @Date: 2022-03-22 15:38:45
 * @LastEditTime: 2022-03-25 12:10:17
-->

<template>
    <ASkeleton>
      <template v-slot:content>
        <div class="problem-pad">
          <a-row :gutter="[4, 8]" type="flex" justify="start" :wrap="true">
            <a-col :offset="2" :xl="3" :lg="5" :md="5" :xs="22">
              <span>年份:</span>
              <a-select v-model:value="problemData.selectYear" :options='options.yearOptions' style="max-width: 120px; min-width: 75px; width: 70%" />
            </a-col>
            <a-col :xl="3" :lg="4" :md="{span:5, offset: 0}" :xs="{span:22, offset: 2}">
              <span>题号:</span>
              <a-input-number :min="1" :max="60" v-model:value="problemData.problemNo" style="max-width: 120px; min-width: 65px; width: 70%"></a-input-number>
<!--              <a-input v-model="problemNo" style="max-width: 120px; min-width: 65px; width: 70%" />-->
            </a-col>
            <a-col :xl="3" :lg="4" :md="{span:5, offset: 0}" :xs="{span:22, offset: 2}">
              <span>学科:</span>
              <a-select v-model:value="problemData.selectSubject" :options='options.subjectOptions' style="max-width: 120px; min-width: 95px; width: 70%" />
            </a-col>
            <a-col :xl="4" :lg="5" :md="{span:7, offset: 0}" :xs="{span:22, offset: 2}">
              <span>标签:</span>
              <a-select v-model:value="problemData.selectTags" mode="tags" placeholder="请输入问题标签" style="max-width: 500px; width: 70%">
                <a-select-option v-for="tag in options.tagOptions" :key="tag">{{ tag }}</a-select-option>
              </a-select>
            </a-col>
            <a-col :xl="2" :lg="{span:2, offset: 0}" :md="{span: 3, offset: 2}" :xs="{span:5, offset: 2}">
              <a-button type="primary" ghost @click="resetEditorContent" >重置</a-button>
            </a-col>
            <a-col :xl="2" :lg="2" :md="{span: 3, offset: 0}" :xs="{span:5, offset: 1}">
              <a-button type="primary" ghost @click="getProblemByYearNumber">搜索</a-button>
            </a-col>
          </a-row>
        </div>
        <div>
          <a-row type="flex" justify="center">
            <a-col :span="2"></a-col>
            <a-col :span="20">
              <VueEditor :modelValue="editor.modelValue" ref="VEditor"/>
            </a-col>
            <a-col :span="2"></a-col>
          </a-row>
          <a-row justify="end">
            <a-col :span="2"></a-col>
            <a-col :span="20">
              <a-button class="submitBtn" type="primary" ghost @click="summitEditor">提交</a-button>
            </a-col>
            <a-col :span="2"></a-col>
          </a-row>
        </div>
      </template>
    </ASkeleton>
</template>

<script lang="ts">
import { Select, Button, Row, Col, message, InputNumber } from 'ant-design-vue'
import ASkeleton from '@/components/Skeleton.vue'
import VueEditor from '@/components/VueVditor.vue'
import { upload408Question, getQesByYearNumber } from '@/service'
import { defineComponent, ref, onMounted } from 'vue'
import { transUrl } from '@/utils/ds'
import { useRouter } from 'vue-router'

interface ProblemData {
  problemNo: number,
  selectYear: string,
  selectSubject: string,
  selectTags: string[],
  editorContent: string,
  problemId: number
}

interface SubOption {
  value: string,
  label: string
}

interface Options {
  yearOptions: SubOption[],
  tagOptions: string[],
  subjectOptions: SubOption[]
}

interface EditorValue {
  modelValue: string
  defaultValue: string
}

interface Question {
  id: number,
  year: string,
  number: number,
  question: string,
  tag: string,
  answer: string,
  type: string,
  subject: string,
  choice: string
}

interface Answer {
  id: number,
  uid: number,
  pid: number,
  answer: string
}

export default defineComponent({
  components: {
    VueEditor,
    ASkeleton,
    ASelect: Select,
    AButton: Button,
    ASelectOption: Select.Option,
    ARow: Row,
    ACol: Col,
    AInputNumber: InputNumber
  },
  name: 'ProblemPad',
  setup () {
    const router = useRouter()
    const problemData = ref<ProblemData>({
      problemNo: 0,
      selectYear: '',
      selectSubject: '',
      selectTags: [],
      editorContent: '',
      problemId: 0
    })
    const options = ref<Options>({
      yearOptions: [],
      tagOptions: [],
      subjectOptions: [
        { value: 'CS', label: '数据结构' },
        { value: 'OS', label: '操作系统' },
        { value: 'NET', label: '计算机网络' },
        { value: 'CCP', label: '组成原理' }
      ]
    })
    const editor = ref<EditorValue>({
      modelValue: '###### 题干\n\n###### 答案：\n',
      defaultValue: '###### 题干\n\n###### 答案：\n'
    })

    const VEditor = ref<InstanceType<typeof VueEditor> | null>()

    function setYearOptions () {
      const today = new Date()
      const year = today.getFullYear()
      for (let i = 2009; i < year; i++) {
        options.value.yearOptions.push({ value: i.toString(), label: i.toString() })
      }
    }

    function getEditorValue ():string {
      if (VEditor.value !== null && VEditor.value !== undefined) {
        return VEditor.value.getEditorValue()
      }
      return ''
    }

    function setEditorValue (value: string) {
      if (VEditor.value !== null && VEditor.value !== undefined) {
        VEditor.value.setEditorValue(value)
      }
    }

    function setEditorContent (value:string) {
      setEditorValue(value)
      // editor.value.modelValue = value
    }

    function resetEditorContent () {
      problemData.value.problemId = 0
      setEditorContent(editor.value.defaultValue)
      problemData.value.problemNo += 1
      problemData.value.selectTags = []
      const pID = problemData.value.problemNo
      if (pID >= 1 && pID <= 11) {
        problemData.value.selectSubject = 'CS'
      } else if (pID >= 12 && pID <= 22) {
        problemData.value.selectSubject = 'CCP'
      } else if (pID >= 23 && pID <= 32) {
        problemData.value.selectSubject = 'OS'
      } else if (pID >= 33 && pID <= 40) {
        problemData.value.selectSubject = 'NET'
      }
    }

    function setProblemInfo (data: Question) {
      problemData.value.problemId = data.id
      problemData.value.problemNo = data.number
      problemData.value.selectYear = data.year
      problemData.value.selectSubject = data.subject
      problemData.value.selectTags = data.tag.split('#')
      let q:string = data.question
      q = transUrl(q)
      let a:string = data.answer
      a = transUrl(a)
      const problemPad = q + '\n' + a
      setEditorContent(problemPad)
    }

    function getProblemByYearNumber () {
      const data:Map<string, string | number> = new Map()
      data.set('year', problemData.value.selectYear)
      data.set('number', problemData.value.problemNo)
      getQesByYearNumber(data)
        .then((response) => {
          const d = response.data
          if (d.code === 0) {
            if (d.data === null) {
              message.error('未找到记录')
            } else {
              setProblemInfo(d.data)
            }
          } else {
            message.error(d.message)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    }

    function summitEditor () {
      const data = problemData.value
      if (data.selectYear === '' || data.problemNo === 0) {
        message.error('请检查年份和题号是否设置')
        return
      }
      if (data.selectSubject === '') {
        message.error('请设置题目所属学科')
        return
      }
      if (data.selectTags.length === 0) {
        message.error('请设置题目标签')
        return
      }
      const content = getEditorValue()
      if (content === '') {
        message.info('内容为空')
        return
      }
      const idx = content.lastIndexOf('######')
      let answer:string, problem:string
      if (idx > 0) {
        answer = content.slice(idx)
        problem = content.slice(0, idx)
      } else {
        problem = content
        answer = ''
      }
      if (answer === '') {
        message.error('请设置答案')
        return
      }
      // console.log(answer)
      const h = answer.indexOf('\n')
      const line = answer.slice(10, h)
      const reg = /[a-z]{1,4}/i
      const choice = line.match(reg)
      if (choice === null || choice.length === 0) {
        message.error('请设置选项')
        return
      }

      const qusData = {
        id: data.problemId,
        year: data.selectYear,
        number: data.problemNo,
        subject: data.selectSubject,
        tag: data.selectTags.join('#'),
        question: problem,
        choice: choice[0]
      }

      const ansData = {
        id: 0,
        answer: answer
      }
      const sendData = {
        question: qusData,
        ans: ansData
      }
      // console.log(qusData)
      upload408Question(sendData)
        .then((response) => {
          if (response.status !== 200) {
            message.info('request failed')
            return
          }
          const resp = response.data
          if (resp.code === 0) {
            problemData.value.problemId = resp.data.pid
            //
            message.success('add 408 qusData success', 0.5)
          } else if (resp.code === 101) {
            message.warn('身份失效 请重新登录', 0.5)
            setTimeout(() => {
              router.replace({ name: 'login' })
            }, 500)
          } else {
            message.error(resp.msg)
          }
        })
        .catch(function (err) {
          console.log(err)
        })
    }

    onMounted(() => {
      setYearOptions()
    })

    return {
      problemData,
      options,
      editor,
      VEditor,
      resetEditorContent,
      getProblemByYearNumber,
      summitEditor
    }
  }
})
</script>

<style scoped>
  .problem-pad {
    padding: 10px 5px 0 5px;
    font-size: 1.2em;
  }
  .submitBtn {
    margin: 20px 5px;
    float: right;
  }
</style>
